var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const { getMd5 } = require('../utils/crypto');
const { loginl, logint, logina } = require('../service/loginService');

//配置二级路径
// 出租方的请求
router.post('/loodl', async function (req, res, next) {

    const { account, password } = req.body;
    // md5加密
    const newPassword = getMd5(password);
    const data = await loginl({ account: account, password: newPassword });
    if (data.status) {
        const token = jwt.sign(
            { account },//要保存的用户信息
            'mark',//秘钥字符串
            { expiresIn: 2000 }//设置token的有效期
        );
        res.send({
            ...data,
            token
        })

    } else {
        res.send(data)
    }
});
// 租方的请求l
router.post('/loodt', async function (req, res, next) {
    const { account } = req.body;
    const data = await logint(req.body);
    if (data.status) {
        const token = jwt.sign(
            { account },//要保存的用户信息
            'mark',//秘钥字符串
            { expiresIn: 2000 }//设置token的有效期
        );
        res.send({
            ...data,
            token
        })

    } else {
        res.send(data)
    }
});
// 管理员的请求
router.post('/looda', async function (req, res, next) {
    const { account } = req.body;
    const data = await logina(req.body);
    if (data.status) {
        const token = jwt.sign(
            { account },//要保存的用户信息
            'mark',//秘钥字符串
            { expiresIn: 2000 }//设置token的有效期
        );
        res.send({
            ...data,
            token
        })

    } else {
        res.send(data)
    }
});
// 判断用户是否登录
router.get('/isLogin', async (req, res) => {
    // 获取token
    const headersToken = req.get('Authorization');
    const token = headersToken.split(' ')[1];
    // 解码token，拿到用户信息
    const { account } = jwt.verify(token, 'mark');
    res.send({
        massage: '身份认证通过,欢迎来到车位管理系统',
        status: 1,
        data: account
    })
})
module.exports = router;